package com.common.utils.cipher;

import com.common.utils.cipher.BASE64;
import com.common.utils.cipher.CipherType;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * @Description:
 */
public class HMAC {
    /**
     * 初始化HMAC密钥
     *
     * @param type 算法，可为空。默认为：CipherType.Hmac_MD5
     * @return
     */
    public static String initMacKey(CipherType type) throws Exception {
        if (type == null) {
            type = CipherType.Hmac_MD5;
        }
        KeyGenerator keyGenerator = KeyGenerator.getInstance(type.getType());
        SecretKey secretKey = keyGenerator.generateKey();
        return BASE64.getInstance().encodeToString(secretKey.getEncoded());
    }

    /**
     * HMAC加密
     *
     * @param plain     明文
     * @param key       key
     * @param type 算法，可为空。默认为：CipherType.Hmac_MD5
     * @return
     */
    public static byte[] encrypt(byte[] plain, String key, CipherType type) throws Exception {
        if (type == null) {
            type = CipherType.Hmac_MD5;
        }
        SecretKey secretKey = new SecretKeySpec(BASE64.getInstance().decode(key), type.getType());
        Mac mac = Mac.getInstance(secretKey.getAlgorithm());
        mac.init(secretKey);
        return mac.doFinal(plain);
    }
}
